<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Services\OSS;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class CouponItem extends Model
{
    protected $dateFormat = 'U';
    //
    protected $table = "lexiang_coupon_item";

    public function add($data)
    {
    	$this->coupon_name = $data['coupon_name'];
        $this->price = $data['price'];
        $this->cost_price = $data['cost_price'];
        $this->lng = $data['lng'];
        $this->lat = $data['lat'];
        $this->shop_id = $data['shop_id'];
        $this->province = $data['province'];
    	$this->city = $data['city'];
    	$this->num = $data['num'];
    	$this->start_time = strtotime($data['starttime']);
    	$this->over_time = strtotime($data['stoptime']);
    	$this->address = $data['address'];
        $this->coupon_desc = $data['desc'];
        $this->is_mail = $data['is_mail'] ?? 0;
        $this->benefit_price = $data['benefit_price'] ?? 0;
    	$this->benefit = $data['benefit'] ?? -1;
    	$file = $data['centerBackground'];
        $fileExt = ltrim($file->getClientOriginalExtension(),'.');
        $fileName = 'CouponCover/'.md5(uniqid(microtime(true),true)).'.'.$fileExt;
        $upRes = OSS::publicUpload(config('aliyun.BucketName'),$fileName,$file);
        $this->cover_img = $fileName;
    	if($this->save()){
    		return ['success'=>true,'code'=>'000','message'=>'发布成功'];
    	}else{
    		return ['success'=>false,'code'=>'006','message'=>'保存出错，请稍后再试！'];
    	}
    }

    public function edit($couponId,$data)
    {
        // try {
            $selfInfo = $this->where('id',$couponId)->first();
            foreach ($data as $key => $value) {
                $selfInfo->$key = $value;
            }
            if($selfInfo->save()){
                return ['success'=>true,'code'=>'000','message'=>'修改成功'];
            }else{
                return ['success'=>false,'code'=>'006','message'=>'保存出错，请稍后再试！'];
            }
        // } catch (\Exception $e) {
        //     return ['success'=>false,'code'=>'006','message'=>'保存出错，请稍后再试！'];
        // }
        
    }

    public function getCouponDistanceAttribute($v)
    {
        return get_distance($this->lat,$this->lng,$this->lat2,$this->lng2);
    }

    public function getCoverImgAttribute($v)
    {
    	return "https://jiashilexiang.oss-cn-beijing.aliyuncs.com/".$v;
    }

    public function getSellAttribute($v)
    {
    	return CouponOrder::where([
    		['coupon_id','=',$this->id],
    		['pay_state','=',1],
    	])->count();
    }

    public function getStartTimeAttribute($v)
    {
    	return date("Y-m-d",$v);
    }

    public function getOverTimeAttribute($v)
    {
    	return date('Y-m-d',$v);
    }

    public function getCreatedAtAttribute($v)
    {
    }

    public function getUpdatedAtAttribute($v)
    {
    	return date('Y-m-d H:i',$v);
    }
}
